
package com.rt.schedulenew.web;

import com.rt.schedulebase.dto.DictServersDto;
import com.rt.schedulebase.dto.ExamApplyDto;
import com.rt.schedulebase.dto.ExamsDto;
import com.rt.schedulebase.entity.DictServers;
import com.rt.schedulebase.entity.Exams;
import com.rt.schedulenew.api.IDictServersService;
import com.rt.schedulenew.api.IExamsService;
import com.rt.schedulenew.api.ISSOService;
import com.rt.schedulenew.utils.annotation.ServiceLimit;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.*;
import com.rt.schedulenew.utils.util.DBUtil;
import com.rt.schedulenew.utils.util.EhCacheUtil;
import com.rt.schedulenew.utils.util.FTPUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping({"/upload"})
public class UploadController {
    private static Logger log = LoggerFactory.getLogger(UploadController.class);

    @Resource
    private IExamsService examsService;
    @Resource
    private IDictServersService dictServerseService;
    @Resource
    private ISSOService SSOService;

    @RequestMapping({"/patch"})
    public JsonResult patch(MultipartHttpServletRequest request, String examNo) throws IOException {
        boolean success = false;
        if (StringUtils.isBlank(examNo)) {
            return JsonResultUtil.failure("检查流水号不能为空！");
        }
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            ExamsDto examsDto = new ExamsDto();
            examsDto.setExamNo(examNo);
            List<Exams> lsExams = examsService.selectList(examsDto);
            if (lsExams.size() == 0) {
                return JsonResultUtil.failure("检查记录为空！");
            }
            DictServersDto dictServersDto = new DictServersDto();
            String svrName = lsExams.get(0).getCommonServer();
            dictServersDto.setSvrName(svrName);
            DictServers dictServers = dictServerseService.getInfo(dictServersDto);
            if (dictServers == null) {
                return JsonResultUtil.failure("文件服务器信息为空！");
            }
            String uploadPath = dictServers.getShareName() + File.separator + lsExams.get(0).getCommonDir();
            int port = 21;
            if (StringUtils.isNotBlank(dictServers.getPort())) {
                port = Integer.parseInt(dictServers.getPort());
            }
            List<MultipartFile> list = request.getFiles("files");
            for (MultipartFile mf : list) {
                String fileName = "Apply" + System.currentTimeMillis() + ".jpg";
                success = FTPUtil.uploadFileFix(dictServers.getIpAddr(), port, dictServers.getWriteUser(), dictServers.getWritePwd(), uploadPath, fileName, mf.getInputStream());
                if (success) {
                    Exams exams = new Exams();
                    exams.setExamNo(examNo);
                    exams.setApplyScaned("1");
                    examsService.update(exams);
                }
            }
        }
        if (success) {
            return JsonResultUtil.success();
        }
        return JsonResultUtil.failure();
    }


    @RequestMapping({"/info"})
    public JsonResult info(@RequestBody ExamsDto examsDto) throws IOException {
        if (StringUtils.isBlank(examsDto.getExamNo())) {
            return JsonResultUtil.failure("检查流水号不能为空！");
        }
        List<Exams> lsExams = examsService.selectList(examsDto);
        if (lsExams.size() == 0) {
            return JsonResultUtil.failure("检查记录为空！");
        }
        DictServersDto dictServersDto = new DictServersDto();
        String svrName = lsExams.get(0).getCommonServer();
        dictServersDto.setSvrName(svrName);
        DictServers dictServers = dictServerseService.getInfo(dictServersDto);
        if (dictServers != null) {
            String commonDir = lsExams.get(0).getCommonDir();
            DictServersDto result = new DictServersDto();
            result.setShareName(dictServers.getShareName());
            result.setUploadPath(commonDir);
            result.setIpAddr(dictServers.getIpAddr());
            result.setPort(dictServers.getPort());
            result.setModifyUser(dictServers.getModifyUser());
            result.setModifyPwdEncrypt(dictServers.getModifyPwdEncrypt());
            return JsonResultUtil.success((Object) result);
        }
        return JsonResultUtil.failure("文件服务器信息为空！");
    }

    @RequestMapping({"/update"})
    public JsonResult update(@RequestBody ExamsDto examsDto) throws IOException {
        if (StringUtils.isBlank(examsDto.getExamNo())) {
            return JsonResultUtil.failure("检查流水号不能为空！");
        }
        Exams exams = new Exams();
        exams.setExamNo(examsDto.getExamNo());
        exams.setApplyScaned("1");
        Boolean i = examsService.update(exams);
        if (i) {
            return JsonResultUtil.success();
        }
        return JsonResultUtil.failure();
    }

    @RequestMapping({"/jdbcTest"})
    public String jdbcTest(String type, String date, String week, String queueName) {
        long startTimeMillis = System.currentTimeMillis();
        if ("1".equals(type)) {
            DBUtil.query1(date, queueName);
        } else {
            DBUtil.query2(week, queueName);
        }
        String s = "响应耗时：" + (System.currentTimeMillis() - startTimeMillis) + "毫秒";
        return s;
    }

    @PostMapping({"/localLock"})
    @LocalLock(key = "localLock:arg[0]")
    public JsonResult localLock(@RequestBody JsonResult jsonResult) {
        return jsonResult;
    }

    @PostMapping({"/synTest"})
    public JsonResult synTest(@RequestBody ExamApplyDto examApplyDto) throws InterruptedException, Throwable {
        StringBuilder lock = new StringBuilder();
        lock.append(examApplyDto.getScheduleDate());
        lock.append(examApplyDto.getScheduleApm());
        synchronized (lock.toString().intern()) {
            log.error(examApplyDto.getScheduleDate() + "============开始");
            Thread.sleep(2000L);
            log.error(examApplyDto.getScheduleDate() + "============结束");
        }
        return JsonResultUtil.success();
    }

    @PostMapping({"/putTokenTest"})
    public JsonResult putTokenTest(@RequestBody String token) throws InterruptedException, Throwable {
        EhCacheUtil.put(ConstantsUtil.EhCacheName.tokenCache.name(), token.intern(), (Serializable) token.intern());
        return JsonResultUtil.success();
    }

    @PostMapping({"/getTokenTest"})
    @ServiceLimit(limitType = ServiceLimit.LimitType.URL)
    public JsonResult getTokenTest(@RequestBody String token) throws InterruptedException, Throwable {
        Boolean isExpired = SSOService.isLogin(token);
        System.out.println("=======" + isExpired);
        return JsonResultUtil.success(isExpired);
    }


    @PostMapping({"/uploadImage"})
    public JsonResult uploadImage(@RequestParam("image") MultipartFile file, HttpServletRequest request) {
        // 获取文件原本的名字
        String originName = file.getOriginalFilename();
        // 判断文件是否是pdf文件
        Set<String> set = new HashSet<>();
        set.add(".png");
        set.add(".jpg");
        set.add(".jpeg");
        // 取出文件的后缀
        int count = 0;
        for (int i = 0; i < originName.length(); i++) {
            if (originName.charAt(i) == '.') {
                count = i;
                break;
            }
        }
        String endName = originName.substring(count); //取出文件类型
        String fileType = originName.substring(count + 1); //文件类型
        String imageName = originName.substring(0, originName.indexOf(".")); //照片原名称
        if (!set.contains(endName)) {
            throw new BusinessException("上传图片格式不正确，必须是png/jpg/jpeg类型！");
        }
        // 创建保存路径
        //日期格式
        SimpleDateFormat sdfY = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdfM = new SimpleDateFormat("MM");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String formatY = sdfY.format(new Date());
        String formatM = sdfM.format(new Date());
        String format = sdf.format(new Date());
        String relativePath = "uploadFiles" + "\\" + formatY + "\\" + formatM;
        String savePath = System.getProperty("user.dir") + "\\" + relativePath;
        // 保存文件的文件夹
        File folder = new File(savePath);
        // 判断路径是否存在,不存在则自动创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String saveName = format + endName;
        try {
            File image = new File(folder + "\\" + saveName);
            if (image.exists()) {
                return JsonResultUtil.failure("上传文件：【" + imageName + "】已存在");
            }
            file.transferTo(new File(folder, saveName));
            String filePath = "uploadFiles" + "/" + formatY + "/" + formatM + "/" + saveName;
            return JsonResultUtil.success(filePath);
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }


    @GetMapping({"/previewImage/**"})
    public void IoReadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String matchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String imageUrl = antPathMatcher.extractPathWithinPattern(matchPattern, path);

        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            //获取图片存放路径
            String imgPath = System.getProperty("user.dir") + "\\" + imageUrl;
            ips = new FileInputStream(imgPath);
            response.setContentType("image/png");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("previewImage:" + imageUrl + " " + e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        } finally {
            out.close();
            ips.close();
        }
    }

}
